<template>
    <div id="instruction-query">
        <div id="header-content">
            <el-form label-width="90px">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品代码(名称):">
                            <el-select v-model="searchParam.fundCodes" clearable filterable multiple collapse-tags size="mini" style="width: 100%">
                                <el-option v-for="i in computedFunds" :key="i.fundCode" :label="i.fundCode + ' ' + i.fundNameSt" :value="i.fundCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="证券代码(名称):">
                            <el-select
                                v-model="searchParam.stockCodes"
                                clearable
                                @clear="getBondCodeList('')"
                                filterable
                                multiple
                                collapse-tags
                                remote
                                :remote-method="getBondCodeList"
                                :loading="selectLoading"
                                size="mini"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in computedStockCode"
                                    :key="item.dictKey"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                    :value="item.dictKey"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="委托方向:">
                            <el-select
                                v-model="searchParam.orderDirections"
                                clearable
                                filterable
                                multiple
                                collapse-tags
                                size="mini"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in computedOrderDirection"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="证券类别:">
                            <el-select v-model="searchParam.stockTypes" clearable filterable multiple collapse-tags style="width: 100%" size="mini">
                                <el-option
                                    v-for="item in computedStockTypeAll"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="业务类型:">
                            <el-select
                                v-model="searchParam.businessTypes"
                                clearable
                                filterable
                                multiple
                                collapse-tags
                                size="mini"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in computedBusinessType"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="2">
                        <el-button type="primary" size="mini" @click="handleButtonClick('search')">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="指令序号:">
                            <el-input placeholder="请输入" v-model="searchParam.instNo" style="width: 100%" size="mini"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="恒生指令序号:">
                            <el-input style="width: 100%" size="mini" v-model="searchParam.dailyInstructionNo" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="指令状态:">
                            <el-select v-model="searchParam.instStatus" size="mini" clearable style="width: 100%">
                                <el-option v-for="(value, key) in instStatusAll" :key="key" :label="value" :value="key"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="下达人:">
                            <el-select v-model="searchParam.directUsers" clearable filterable multiple collapse-tags size="mini" style="width: 100%">
                                <el-option
                                    v-for="item in computedOrderUsers"
                                    :key="item.dictKey"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" size="mini" @click="handleButtonClick('layout')">布局设置</el-button>
                        <el-button size="mini" @click="handleButtonClick('hide')">{{ hideVisible ? '展开' : '隐藏' }}</el-button>
                    </el-col>
                </el-row>
                <el-row v-if="!hideVisible">
                    <el-col :span="5">
                        <el-form-item label="下达日期:">
                            <el-date-picker
                                v-model="searchParam.directDate"
                                type="date"
                                placeholder="年/月/日"
                                value-format="yyyyMMdd"
                                format="yyyy/MM/dd"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="数据来源:">
                            <el-select v-model="searchParam.sourceType" clearable multiple collapse-tags size="mini" style="width: 100%">
                                <el-option v-for="(value, key) in sourceType" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" v-show="SHOW_SECURITY">
                        <el-form-item label="组合编码(名称):">
                            <el-select v-model="searchParam.fundAccountCodes" style="width: 100%" size="mini" multiple collapse-tags filterable>
                                <el-option
                                    v-for="i in fundAccountCodeSelectData"
                                    :key="i.fundAccountCode"
                                    :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                    :value="i.fundAccountCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div id="main-content">
            <div style="height: calc(100% - 40px)">
                <el-table
                    auto-resize
                    resizable
                    stripe
                    :data="dataSource"
                    border
                    v-loading="tableLoading"
                    element-loading-text="加载中"
                    size="mini"
                    height="100%"
                    ref="table"
                    @row-click="handleRow"
                    style="cursor: pointer; width: 100%"
                    highlight-current-row
                    highlight-hover-row
                    :default-sort="{ prop: sortProp, order: sortOrder }"
                    @sort-change="changeTableSort"
                >
                    <template v-for="(item, index) in showFieldList">
                        <el-table-column
                            :show-overflow-tooltip="item.id != 'fundCode' && item.id != 'instructionNo'"
                            :key="index"
                            :label="item.content"
                            :prop="item.id"
                            :min-width="item.minWidth"
                            :width="item.width"
                            :sortable="!(item.sortable === false) && 'custom'"
                            :sort-orders="['ascending', 'descending']"
                            :fixed="['fundCode', 'instructionNo', 'batchNo'].includes(item.id) ? 'left' : undefined"
                        >
                            <template slot-scope="scope">
                                <span v-if="item.id == 'stockType'">
                                    {{ getBondType(scope.row[item.id]) || '--' }}
                                </span>
                                <span v-else-if="item.id == 'bulkType'">
                                    {{ scope.row.bulkType && scope.row.bulkType !== '0' ? Invest.bulkType[scope.row.bulkType] : '--' }}
                                </span>
                                <span v-else-if="item.id == 'intoInvestType'">
                                    {{ scope.row['orderDirection'] === '基金转换' ? scope.row.investType || '--' : '--' }}
                                </span>
                                <span v-else-if="item.type == 'func'">
                                    {{ item.funcBody(scope.row[item.id], scope.row) || '--' }}
                                </span>
                                <span v-else-if="item.type == 'status'">
                                    {{ item.statusKV[scope.row[item.id]] || '--' }}
                                </span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <risk-pagination :paging="pages" @page-change="handleCurrentChange"></risk-pagination>
            <RiskTableLayout
                title="页面布局"
                :visible.sync="layoutDialog"
                :field-list="tableColumns"
                :selected-field-list="selectedFieldList"
                :fixed-field-list="fixedFieldList"
                :table-name="'COMPREHENSIVE_INST_INFO'"
                @on-submit="onSubmit"
            />
        </div>
        <div id="bottom-content" v-loading="tabsLoading">
            <el-tabs v-model="activeKey" @tab-click="handleClick">
                <el-tab-pane label="指令明细" name="detail" class="inst-detail">
                    <div
                        style="height: calc(40vh - 70px); padding: 4px 10px; overflow: auto"
                        :key="tabskey + 'tabskey'"
                        element-loading-text="加载中"
                    >
                        <div class="detail-row">
                            <span v-for="item in defaultFieldsReal" :key="item.val + item.name">
                                {{ item.name ? item.name + '：' : '' }}
                                <span v-if="item.val == 'stockType'" style="color: blue">
                                    {{
                                        instDetailData.stockType
                                            ? stockTypeAll.find(item => item.dictKey == instDetailData.stockType).dictKeyName
                                            : ''
                                    }}
                                </span>
                                <span v-else-if="item.name == ''"> </span>
                                <span v-else-if="item.type === 'func'" style="color: blue">
                                    {{ hasClick ? item.funcBody(instDetailData[item.val], instDetailData) || '--' : '' }}
                                </span>
                                <span v-else style="color: blue">
                                    {{ instDetailData[item.val] ? instDetailData[item.val] : hasClick ? '--' : '' }}
                                </span>
                            </span>

                            <span v-for="item in fileds" :key="item.val + item.name">
                                {{ item.name ? item.name + '：' : '' }}
                                <span v-if="item.id == 'stockType'" style="color: blue">
                                    {{ getBondType(scope.row[item.id]) || '--' }}
                                </span>
                                <span v-else-if="item.type == 'func'" style="color: blue">
                                    {{ item.funcBody(instDetailData[item.val], instDetailData) || '--' }}
                                </span>
                                <!-- 转融通 -->
                                <span v-else-if="['instAmount', 'rate'].includes(item.val)" style="color: blue">
                                    {{ instDetailData[item.val] ? numberFormat(instDetailData[item.val], 2) : '0.00' }}
                                </span>
                                <span v-else-if="item.val == 'deadline'" style="color: blue">
                                    {{ numberFormat(instDetailData[item.val]) || '--' }}
                                </span>
                                <!--  -->
                                <span v-else style="color: blue">{{ instDetailData[item.val] || '--' }} </span>
                            </span>
                        </div>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="指令证券" name="stock">
                    <div style="height: calc(40vh - 70px); padding: 4px 5px">
                        <risk-table :msg="instStockMsg"></risk-table>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-if="showPledgeTab" label="指令质押券" name="pledge">
                    <div style="height: calc(40vh - 70px); padding: 4px 5px">
                        <risk-table :msg="instPledgeMsg"></risk-table></div
                ></el-tab-pane>
                <el-tab-pane label="指令结果" name="result">
                    <div style="height: calc(40vh - 70px); padding: 4px 5px">
                        <risk-table
                            :msg="instResultMsg"
                            @handleBtn="handleBtnLook"
                            :key="instResultMsgNumKey + 'instResultMsgNumKey'"
                            v-if="activeKey === 'result'"
                        ></risk-table>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { Vue, Component, Prop } from 'vue-property-decorator';
import * as moment from 'moment';
import { dateFormat, PrefixInteger, timeFormat, numberFormat, unitShow, sortBy, getConfigItem, uniqueFunc, changeOptions } from '@/utils/tools';
import RiskTable from '@/common/components/risk-table.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import XEUtils from 'xe-utils';
import ColumnUtil from '../risk-time/utils/column-util';
import InstructionColumnUtil from './instruction-query/instruction-column-util';
import { getSystem } from '@/utils/user-util';
import RiskPagination from '@/common/components/risk-pagination.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'InstructionQueryManage',
    components: {
        RiskTable,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class InstructionQueryManage extends Vue {
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    ColumnUtil = new ColumnUtil();
    InstructionColumnUtil = new InstructionColumnUtil();
    moment = moment;
    timeFormat = timeFormat;
    dateFormat = dateFormat;
    numberFormat = numberFormat;
    Invest = new Invest();
    private activeKey: string = 'detail'; //  指令当前tabKey

    private tabsLoading: boolean = false; // tab表格加载

    private tableLoading: boolean = false; // 表数据加载

    private selectLoading: boolean = false; // 下拉框加载

    private dataSource: any[] = []; // 指令表数据

    private clickRecord: any = {}; // 当前主表格点击的条目

    private fundCodeSelectData: any[] = []; // 下拉表格

    private instResultMsgNumKey: number = -1; // 指令结果渲染

    private instDetailData: any = {}; // 指令明细

    private layoutDialog: boolean = false; // 布局是否展示

    private investPriceSelectData: any = {}; // 价格模式下拉框数据

    private bondCodeSelectData: any[] = []; // 证券代码下拉框数据

    private stockTypeAll: any[] = []; // 证券类别

    private sortProp: string = ''; // 排序字段

    private sortOrder: string = ''; // 排序方式

    private fileds: any[] = []; // 根据指令类型展示拼接字段

    private hasClick: boolean = false; // 是否已点击

    private showPledgeTab: boolean = false; // 是否显示质押券标签页

    private sourceType = DictionConstUtil.SourceType; // 数据来源
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    hideVisible: boolean = true; // 是否隐藏
    // 明细中默认展示字段
    defaultFieldsReal: any[] = [];

    private defaultFields: any[] = this.InstructionColumnUtil.defaultDetailColumn;

    // 默认展示明细字段
    private searchParam = {
        bankBondAssetTypes: [],
        bankBondMarketTypes: [],
        businessTypes: [],
        depositStockTypes: [],
        directUsers: [],
        exchangeAssetTypes: [],
        exchangeMarketTypes: [],
        exchangeStockTypes: [],
        fundCodes: [],
        instNo: '',
        instStatus: '1',
        orderDirections: [],
        outOrderCode: '',
        paging: {
            currentPage: 0,
            pageSize: 0,
        },
        stockCodes: [],
        fundAccountCodes: [],
        stockTypes: [],
        userCode: '',
        sourceType: [],
    }; // 查询条件

    // 业务类型
    private businessTypeNameAll = {
        // '1': '交易所业务',
        // '2': '银行间业务',
        // '4': '期货业务',
        // A: '开放式基金',
        // B: '存款类',
        // C: '网下申购',
        // D: '债券一级市场',
        // E: '交易所大宗交易',
        // I: '上交所固定收益平台',
    };

    // 指令状态
    private instStatusAll = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
    };

    // 分页
    private pages: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };

    // 指令证券
    private instStockMsg = {
        returnData: {},
        dataKey: 'list',
        title: [],
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    private instPledgeMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instPledgeColumns,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    // 指令结果
    private instResultMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instResultColumns,
        localSearch: true,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instructionNo', minWidth: 120 },
        { content: '指令批号', id: 'batchNo', minWidth: 120 },
        { content: '产品代码', id: 'fundCode', minWidth: 120 },
    ];
    // 全部表格列
    private tableColumns: any[] = this.InstructionColumnUtil.tableColumns;

    private showFieldList: any[] = []; // 要显示的表格列

    private selectedFieldList: any[] = []; // 已选择字段列表(不包括固定字段)

    invest = new Invest();

    private funds: any[] = []; // 产品代码

    private fundAccounts: any[] = []; // 产品组合信息

    private orderDirection: any[] = []; // 委托方向

    private orderUsers: any[] = []; // 下达人下拉列表

    private tabskey: number = -1;

    private marketCodes: any = {};
    beforeUpdate() {
        this.$nextTick(() => {
            // 在数据加载完，重新渲染表格
            (this.$refs as any).table.doLayout();
        });
    }

    simulateInstColumns = [
        { id: 'simulate', content: '是否模拟指令', sortable: false, minWidth: 140, type: 'status', statusKV: { '0': '不是', '1': '是' } },
        { id: 'simulateMessage', content: '模拟指令信息', sortable: false, minWidth: 140 },
    ];
    // showSimulateInst: boolean = false; // 是否显示调整资产数据
    async mounted() {
        if (this.SHOW_SECURITY) {
            // this.$axios.get('/asset/list/byFundCode').then((res: any) => {
            //     this.assetCodeSelectData = res;
            // });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fundAccountCodeSelectData = res;
            });
        }
        const showSimulateInst = (getSystem().find(item => item.paramKey == 'SHOW_SIMULATE_INST') || {}).paramValue || false;

        if (showSimulateInst) {
            // 显示
            this.tableColumns = this.tableColumns.concat(this.simulateInstColumns);
        }

        this.defaultFieldsReal = this.ColumnUtil.handleColumns(this.defaultFields, 'val', 'fundNameSt', [
            { name: '资产单元编号', val: 'assetCode' },
            { name: '资产单元名称', val: 'assetName' },
        ]);

        this.getDict();

        this.getInstruction(this.searchParam, this.pages);

        let columns = this.InstructionColumnUtil.instStockColumns;
        this.instStockMsg.title = columns;
        // this.instStockMsg.title = this.InstructionColumnUtil.instStockColumn;

        await this.FNTableLayout();
    }

    // 产品代码已选项前置
    get computedFunds() {
        // if (this.searchParam.fundCodes && this.searchParam.fundCodes.length) {
        let funds = changeOptions(this.searchParam.fundCodes, this.funds, 'fundCode');
        return funds;
        // } else {
        //     return this.funds;
        // }
    }

    // 证券代码已选项前置
    get computedStockCode() {
        // if (this.searchParam.stockCodes && this.searchParam.stockCodes.length) {
        let stockCode = changeOptions(this.searchParam.stockCodes, this.bondCodeSelectData, 'dictKey');
        return stockCode;
        // } else {
        //     return this.bondCodeSelectData;
        // }
    }

    // 委托方向已选项前置
    get computedOrderDirection() {
        let orderDirection = changeOptions(this.searchParam.orderDirections, this.orderDirection, 'dictKey');
        return orderDirection;
    }

    // 证券类别已选项前置
    get computedStockTypeAll() {
        let stockTypeAll = changeOptions(this.searchParam.stockTypes, this.stockTypeAll, 'dictKey');
        return stockTypeAll;
    }

    // 业务类型已选项前置
    get computedBusinessType() {
        let businessTypeNameAll = changeOptions(this.searchParam.businessTypes, this.businessTypeNameAll, 'dictKey');
        return businessTypeNameAll;
    }

    // 下达人已选项前置
    get computedOrderUsers() {
        let orderUsers = changeOptions(this.searchParam.directUsers, this.orderUsers, 'dictCode');
        return orderUsers;
    }

    // 字段值
    async getDict() {
        // 业务类型
        this.$axios.get('/dict/businessType/all').then(res => {
            this.businessTypeNameAll = res;
            // this.businessTypeNameAll = DictionConstUtil.ListToPojo(res);
        });

        // 产品数据
        this.funds = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);

        // 产品组合信息
        (await DictionConstUtil.FNFundAccount()).forEach(item => {
            this.fundAccounts[item.fundCode] = item.fundAccounts;
        });

        // 订单方向
        this.orderDirection = await DictionConstUtil.FNTradeDirection();

        // 证券类别
        this.stockTypeAll = await DictionConstUtil.FNStockType();

        // 获取价格模式下拉框数据

        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPriceSelectData = DictionConstUtil.ListToPojo(priceTypeTemp);
        // 下达人下拉列表
        this.$axios.post('/instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });

        this.marketCodes = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());

        // 新增部分，发送Ajax获取  “证券代码”列表
        await this.getBondCodeList('');
    }

    // 获取证券代码下拉框数据
    private getBondCodeList(e: string) {
        this.selectLoading = true;
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/dict/comprehensive/stock/select', {
                    dictKey: e,
                    dictKeyName: e,
                })
                .then((res: any) => {
                    this.bondCodeSelectData = res || [];
                    this.selectLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.selectLoading = false;
                    reject(err);
                });
        });
    }

    //  获取指令信息
    private getInstruction(param: any, paging: any): void {
        this.tableLoading = true;
        this.$axios
            .post('/comprehensive/inst/query', {
                ...param,
                paging: paging,
            })
            .then((res: any) => {
                if (res.list && res.list.length > 0) {
                    this.dataSource = res.list;
                    this.pages.total = res.total;
                } else {
                    this.dataSource = [];
                    this.pages.total = 0;
                }
                let keyIndex = this.dataSource.findIndex(item => item.instructionNo == this.clickRecord.instructionNo);
                if (keyIndex || keyIndex === 0) {
                    (this.$refs as any).table.setCurrentRow(this.dataSource[keyIndex]);
                }
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 点击单行
    private handleRow(record: any): void {
        console.log(record, 'record');
        if (record.orderDirection == '直接还券') {
            record.repayMode = '即时还券';
        }
        this.hasClick = true;
        if (record.businessType === '2' && record.orderDirection === '融资回购') {
            this.showPledgeTab = true;
        } else {
            this.showPledgeTab = false;
        }
        if (record.instClass != '1') {
            if (record.businessType === 'A') {
                this.getFields('A');
            } else {
                this.getFields(record.instClass);
            }
        } else {
            // 交易所债券
            this.defaultFieldsReal = this.ColumnUtil.handleColumns(this.defaultFields, 'val', 'fundNameSt', [
                { name: '资产单元编号', val: 'assetCode' },
                { name: '资产单元名称', val: 'assetName' },
            ]);
            if (record.businessType === '6' && ['P', 'Q'].includes(record.orderDirectionCode)) {
                this.getFields('6');
            } else {
                this.fileds = [];
            }
        }

        this.clickRecord = record;
        this.instDetailData = record;

        let detailQuery = {
            historyDate: record.historyDate || 0,
            instClass: record.instClass || '',
            instNo: record.instructionNo || '',
            instStatus: record.instStatus || '',
            outOrderCode: record.outOrderCode || '',
            serialNo: record.serialNo || 0,
            userCode: '',
            showError: true, // 产品true, 浦银false,
            dailyInstructionNo: record.dailyInstructionNo || '', // 恒生指令序号
            indexDailyModify: record.indexDailyModify || '', // 恒生指令修改次序
            sourceType: record.sourceType, // 数据来源类型 (判断是否外部指令下达) 这里默认查询内部的指令
        };
        this.tabsLoading = true;
        this.$axios
            .post('/comprehensive/inst/detail', detailQuery)
            .then((response: any) => {
                let res = response.instructionAllResult;
                if (res) {
                    // 指令证券
                    let instStockDataSource = [];
                    // 业务类型为"融资融券信用业务"
                    if (record.businessType === 'x') {
                        instStockDataSource = res.rzrqStocks;
                    } else if (record.instClass == '6') {
                        instStockDataSource = res.securityLoans;
                        instStockDataSource.forEach((item, i) => {
                            item.instPrice = item.instAmount ? item.instBalance / item.instAmount : '0';
                        });
                    } else {
                        if (res.deposits && res.deposits.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.deposits);
                        }
                        if (res.repos && res.repos.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.repos);
                        }
                        if (res.stocks && res.stocks.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.stocks);
                        }
                        if (record.instClass === '4' && record.sourceType === '2') {
                            instStockDataSource.forEach(ele => {
                                ele.instPrice = Number(ele.instPrice || '0') * 100;
                            });
                        }
                    }

                    instStockDataSource.forEach((item, i) => {
                        item.key = item.serialNo + '-' + i;
                        item.stockCode = this.clickRecord.stockCode;
                        item.stockNameSt = this.clickRecord.stockName;
                        item.marketName = this.clickRecord.marketName;
                    });

                    this.$set(this.instStockMsg.returnData, 'list', instStockDataSource);

                    if (res.results && res.results.length > 0) {
                        res.results.forEach((item, i) => {
                            item.key = item.entryCode + '-' + i;
                            item.stockCode = this.clickRecord.stockCode;
                        });
                        res.results = res.results.sort(sortBy('thresholdType', 'desc'));
                    }
                    this.$set(this.instResultMsg.returnData, 'list', res.results || []);
                    //  res.results.filter(item => item.thresholdType != '4')

                    let instPledgeDataSource = res.pleds;
                    // 处理质押券数据
                    instPledgeDataSource.forEach(ele => {
                        // 交易市场
                        ele.marketName = this.marketCodes[ele.marketCode];
                        // 券面总额
                        ele.totalFacePrice = ele.totalFacePrice / 10000;
                        // 成交金额
                        ele.balance = (ele.totalFacePrice * ele.pledgeRate) / 100;
                    });
                    this.$set(this.instPledgeMsg.returnData, 'list', instPledgeDataSource);
                }

                if (response.instructionDetail) {
                    this.instDetailData = Object.assign(this.instDetailData, response.instructionDetail);
                    if (
                        record.instClass === '4' &&
                        record.sourceType === '2' &&
                        ['融资回购', '融券回购'].includes(this.instDetailData.orderDirection)
                    ) {
                        this.instDetailData.repoRate = Number(record.repoRate || '0') * 100;
                    }
                }
                this.tabskey++;
                this.tabsLoading = false;
            })
            .catch(() => {
                this.tabskey++;
                this.tabsLoading = false;
            });
    }

    // 详细信息tabs切换
    private handleClick(tab, event) {}

    // 按钮点击
    private handleButtonClick(action: string): void {
        if (action === 'search') {
            // 获取条件，开始查找
            this.pages.currentPage = 1;
            this.getInstruction(this.searchParam, this.pages);
        } else if (action === 'layout') {
            this.layoutDialog = true;
        } else if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
            console.log(this.hideVisible, 'hideVisible');
        }
    }

    // 布局回调
    onSubmit(data) {
        this.FNTableLayout();
    }

    // 下达人
    private getDirectUser(value: string): any {
        let actual = this.orderUsers.find(item => item.dictCode == value) || {};
        return value ? actual.dictKeyName : '--';
    }

    // 表格布局
    private async FNTableLayout() {
        let columns: any = await new Promise((resolve, reject) => {
            this.$axios
                .get('/tableLayout/query/COMPREHENSIVE_INST_INFO')
                .then((res: any) => {
                    res = res ? JSON.parse(res.replace(/\\/g, '\\\\')) : null;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        let realColumns = [];
        if (!columns) {
            // 如果布局设置为空时 则说明未设置过布局 这里给出默认值
            realColumns = this.tableColumns.filter(item => item.id != 'instructionNo' && item.id != 'fundCode');
        } else {
            // realColumns = columns;
            realColumns = columns.map(item => this.tableColumns.find(ele => ele.id === item.id)); //
        }

        this.selectedFieldList = realColumns;
        this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        this.showFieldList = uniqueFunc(this.showFieldList, 'id');
    }

    // 分页
    private handleCurrentChange(curPage: number): void {
       // this.pages.currentPage = curPage;
        this.getInstruction(this.searchParam, this.pages);
    }

    // 指令明细字段
    private getFields(type: string): void {
        this.defaultFieldsReal = XEUtils.clone(this.defaultFields, true);
        // 开放式基金
        if (type === 'A') {
            this.fileds = this.InstructionColumnUtil.otherCWOpenFields;
        } else if (type == '6') {
            this.defaultFieldsReal[6].name = '指令数量(篮)';
            this.fileds = this.InstructionColumnUtil.ETFOrderInfoColumns;
            console.log(this.fileds, 'this.fileds');
        } else {
            this.defaultFieldsReal[5] = {
                name: '',
                val: 'name1',
            };
            this.defaultFieldsReal[6] = {
                name: '',
                val: 'name2',
            };
            switch (type) {
                // 银行间债券
                case '2':
                    this.fileds = this.InstructionColumnUtil.otherBankBondFields;
                    this.defaultFieldsReal[4] = {
                        name: '总应计利息(元)',
                        val: 'totalInterest',
                        type: 'func',
                        funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
                    };
                    break;
                case '3':
                    // 一级债券
                    this.fileds = this.InstructionColumnUtil.otherPrimaryBondFields;
                    this.defaultFieldsReal[4] = {
                        name: '投标金额(元)',
                        val: 'instBalance',
                        type: 'func',
                        funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
                    };
                    break;
                case '4':
                    this.fileds = this.InstructionColumnUtil.otherBankHgFields;
                    this.defaultFieldsReal[4] = {
                        name: '',
                        val: 'name3',
                    };
                    break;
                case '5':
                    //  存款指令
                    this.fileds = this.InstructionColumnUtil.otherDepositFields;
                    this.defaultFieldsReal[4] = {
                        name: '',
                        val: 'name4',
                    };
                    break;
                case '6':
                    this.defaultFieldsReal[4] = {
                        name: '',
                        val: 'name4',
                    };
                    this.defaultFieldsReal.splice(17, 3);
                    this.fileds = [
                        { name: '期限(天)', val: 'deadline' },
                        { name: '费率(%)', val: 'rate' },
                        { name: '融出数量(股)', val: 'instAmount', minWidth: 120 },
                        // orderAmount  改成 instAmount
                        { name: '交易对手编码', val: 'opponentCode', minWidth: 120 },
                        { name: '交易对手名称', val: 'opponentName', minWidth: 120 },
                        { name: '币种', val: 'curName' },
                        { name: '交易市场', val: 'marketName' },
                    ];
                    break;
                case 'x':
                    this.defaultFieldsReal.splice(17, 0, { name: '还券模式', val: 'repayMode' });
                    break;
                default:
                    this.fileds = [];
                    break;
            }
        }
        this.defaultFieldsReal = this.ColumnUtil.handleColumns(this.defaultFieldsReal, 'val', 'fundNameSt', [
            { name: '资产单元编号', val: 'assetCode' },
            { name: '资产单元名称', val: 'assetName' },
        ]);
    }

    // 指令结果查看按钮点击
    private handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.clickRecord.instStatus == '0', clickRecord: this.clickRecord });
    }

    // 排序改变
    private changeTableSort(column: any): void {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        this.searchParam['sort'] = this.findName(column.prop, sortType);
        this.pages.currentPage = 1;
        this.getInstruction(this.searchParam, this.pages);
    }

    // 获取排序字段名称
    private findName(name: string, order: string): string {
        let value = '';
        switch (name) {
            case 'dailyInstructionNo':
                value = 'N_DAILY_INSTRUCTION_NO' + ' ' + order;
                break;
            case 'instructionNo':
                value = 'N_INST_NO' + ' ' + order;
                break;
            case 'fundCode':
                value = 'C_FUND_CODE' + ' ' + order;
                break;
            case 'fundNameSt':
                value = 'C_FUND_NAME_ST' + ' ' + order;
                break;
            case 'fundAccountCode':
                value = "TO_NUMBER(REGEXP_REPLACE(C_FD_AC_CODE, '[^0-9]', ''))" + ' ' + order;
                break;
            case 'fundAccountName':
                value = 'C_FD_AC_NAME' + ' ' + order;
                break;
            case 'stockCode':
                value = 'C_STOCK_CODE' + ' ' + order;
                break;
            case 'stockName':
                value = 'C_STOCK_NAME' + ' ' + order;
                break;
            case 'businessTypeName':
                value = 'C_BUSINESS_TYPE_NAME' + ' ' + order;
                break;
            case 'orderDirection':
                value = 'C_DIRECTION_NAME' + ' ' + order;
                break;
            case 'investType':
                value = 'C_INVEST_TYPE_NAME' + ' ' + order;
                break;
            case 'priceType':
                value = 'C_ORDER_PRICE_TYPE' + ' ' + order;
                break;
            case 'instPrice':
                value = 'N_INST_PRICE' + ' ' + order;
                break;
            case 'instAmount':
                value = 'N_INST_AMOUNT' + ' ' + order;
                break;
            case 'instBalance':
                value = 'N_INST_BALANCE' + ' ' + order;
                break;
            case 'curCode':
                value = 'C_CUR_CODE' + ' ' + order;
                break;
            case 'marketName':
                value = 'C_MARKET_NAME' + ' ' + order;
                break;
            case 'directUserName':
                value = 'C_DIREACT_USER_NAME' + ' ' + order;
                break;
            case 'directDate':
                value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
                break;
            case 'sourceType':
                value = 'C_SOURCE_TYPE' + ' ' + order;
                break;
            case 'instStatus':
                value = 'C_INST_STATUS' + ' ' + order;
                break;
            case 'assetCode':
                value = "TO_NUMBER(REGEXP_REPLACE(C_ASSET_CODE,'[^0-9]',''))" + ' ' + order;
                break;
            case 'assetName':
                value = 'C_ASSET_NAME' + ' ' + order;
                break;
            default:
                value = '';
                break;
        }
        return value;
    }

    // 证券类别
    private getBondType(value: string): string {
        return (this.stockTypeAll.find(item => item.dictKey == value) || {}).dictKeyName;
    }
}
</script>
<style lang="scss" scoped>
/deep/ .el-input__inner {
    height: 28px;
    line-height: 28px !important;
}
/deep/.el-input__icon {
    line-height: 42px !important;
}
// 滚动条的宽度
/deep/.el-table__body-wrapper::-webkit-scrollbar {
    width: 7px; // 横向滚动条
    height: 7px; // 纵向滚动条 必写
}
// 滚动条的滑块
/deep/.el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #c9c9c9;
    border-radius: 3.5px;
}
#instruction-query {
    height: calc(100vh - 50px);
    padding: 10px 20px;
    #header-content {
        border: 1px solid #d7d7d7;
        // height: 100px;
        .el-row {
            display: flex;
            align-items: center;
        }
        .el-button {
            float: right;
            margin-right: 4px;
        }
        .el-form-item {
            margin-bottom: 5px;
            /deep/.el-form-item__label {
                color: black;
                padding: 0px !important;
            }
        }
        .el-col-5 {
            /deep/.el-form-item__label {
                width: 110px !important;
            }
            /deep/.el-form-item__content {
                margin-left: 110px !important;
            }
        }

        // 日期选择器、下拉框
        /deep/ .el-input--suffix {
            .el-input__suffix {
                right: 4px;
            }
            .el-input__inner {
                padding-right: 20px;
            }
        }
    }
    #main-content {
        border: 1px solid #ccc;
        margin-top: 10px;
        height: calc(60vh - 150px);
        /deep/.el-table {
            th {
                padding: 5px 0 !important;
                background-color: #e8f3ff !important;
                .cell {
                    white-space: nowrap; /* 文本在一行显示，不换行 */
                    text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本。*/
                    overflow: hidden; /* 超出部分隐藏 */
                }
            }
        }
    }
    #bottom-content {
        margin-top: 10px;
        border: 1px solid #ccc;
        height: calc(40vh - 20px);
        .inst-detail {
            // 滚动条的宽度
            ::-webkit-scrollbar {
                width: 7px; // 横向滚动条
                height: 7px; // 纵向滚动条 必写
            }
            // 滚动条的滑块
            ::-webkit-scrollbar-thumb {
                background-color: #c9c9c9;
                border-radius: 3.5px;
            }
        }
        .detail-row {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            grid-gap: 4px;
            color: black;
            margin-bottom: 6px;
            width: max-content;
            min-width: 100%;
            span {
                padding: 5px 0;
            }
        }
    }
}
#instruction-query #header-content /deep/ .el-form-item .el-form-item__label {
    font-size: 13px;
}
/deep/ .el-pagination {
    padding: 6px 6px 6px 0 !important;
}

/deep/ .el-select__tags {
    flex-wrap: nowrap;
}

/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 74%;
    max-width: fit-content;
    padding: 0px;
    margin: 2px 0 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        // max-width: 40px;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
/deep/ .el-select {
    .el-tag__close.el-icon-close {
        right: 1px;
    }
}
</style>
